require 'digest/md5'
module WWW
  class Tkd
    class TbUser < ActiveRecord::Base
      attr_reader :is_newer
      attr_writer  :is_newer
      #将旺旺传递的用户信息保存
      def self.save_from_aliww(domain_login_id,user_id,app_instance_id,hash_code,is_seller,is_bops)
        #安全校验
        if !WWW::Tkd::Utils::Misc.validate_parameter user_id,app_instance_id,hash_code,is_seller
          return nil
        end
        if domain_login_id==nil
          return nil
        end
        domain_login_id = WWW::Tkd::Utils::Misc.get_domain_login_id_from_ww domain_login_id
        tb_user = TbUser::find_by_domain_login_id(domain_login_id)
        if tb_user==nil
          tb_user = WWW::Tkd::TbUser.new
          tb_user.user_id =user_id
          tb_user.app_instance_id = app_instance_id
          tb_user.is_seller=is_seller
          tb_user.domain_login_id=domain_login_id
          tb_user.sip_sessionid=generate_random_string
          tb_user.is_newer = true
          tb_user.save
        else
          tb_user.is_newer = false
          if tb_user.sip_sessionid==nil
            tb_user.sip_sessionid=generate_random_string
            tb_user.save
          end
        end
        #用户身份
        if tb_user.is_seller!=is_seller
          tb_user.is_seller=is_seller
          tb_user.save
        end
        if is_bops==false
          #在非BOPS来源就更新用户最近20天的登录次数
          WWW::Tkd::Gold::Service::User.update_login_liveness tb_user
        end
        return tb_user
      end
      #将alisoft用户对象转换为Tkd对象
      def self.save_from_alisoft alisoft_user,is_seller
        tb_user = TbUser::find_by_domain_login_id(alisoft_user.domain_login_id)
        if tb_user==nil
          tb_user = WWW::Tkd::TbUser.new
          tb_user.user_id = alisoft_user.user_id
          tb_user.app_instance_id = alisoft_user.app_instance_id
          tb_user.domain_login_id = alisoft_user.domain_login_id
          tb_user.sip_sessionid = generate_random_string
          tb_user.is_seller = is_seller
          tb_user.save
        end
        tb_user.domain_login_id=alisoft_user.get_domain_login_id
        tb_user.save
        #更新用户最近20天的登录次数
        WWW::Tkd::Gold::Service::User.update_login_liveness tb_user
        return tb_user
      end
      #更新用户的淘宝账号
      def self.update_domain_login_id id,domain_login_id
        user = self.find id
        if user!=nil && domain_login_id!=nil
          user.domain_login_id=domain_login_id
          user.save
        end
      end
      #更新sip_session
      def self.refresh_sip_sessionid id
        tb_user = TbUser::find_by_id(id)
        tb_user.sip_sessionid=generate_random_string
        tb_user.save
        tb_user.sip_sessionid
      end
      #获得随机字符串
      def self.generate_random_string(length=10)
        string = ""
        chars = ("A".."Z").to_a
        length.times do
          string << chars[rand(chars.length-1)]
        end
        string
      end

    end
  end
end
